package de.maedn.server;

import java.io.IOException;
import java.security.Principal;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UserService userService = UserServiceFactory.getUserService();

        String thisURL = req.getRequestURI();

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println("<html><head><meta http-equiv='Content-Type' content='Type=text/html; charset=utf-8'></head><body>");
            
        if (userService.isUserLoggedIn()) {
            Principal principal = req.getUserPrincipal();
            String account = principal.getName();

            EntityManager em = EMF.createEntityManager();
			String select = "SELECT FROM User u WHERE u.account=:account";
			Query query = em.createQuery(select).setParameter("account", account);
			User user = null;
			try {
				user = (User)query.getSingleResult();
			} catch (NoResultException e) {
				;
			}
			
            resp.getWriter().println("<p>Hallo, " + principal.getName() + "! <a href=\"" + userService.createLogoutURL(thisURL) + "\">Hier</a> kannst du dich abmelden.</p>");

            if (user==null) {
                resp.getWriter().println("<p>Neuen Benutzer automatisch anlegen.");

                user = new User(account, account);
            	em.persist(user);
            	em.close();
			} else {
                resp.getWriter().println("<p>Willkommen zur&uuml;ck.");
                resp.getWriter().println(user.getName());
  			}
            resp.getWriter().println("<script>"+ "window.location.href='/index.html"+"';</script>");
        } else {
            resp.getWriter().println("<p>Bitte <a href=\"" + userService.createLoginURL(thisURL) + "\">anmelden</a>.</p>");
        }
    }
}